/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.edu.zjut.ces.service.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author user
 */
public class BaseService {
    private static EntityManagerFactory emf;
    private EntityManager em;

    protected EntityManager getEm(){
        return em;
    }

        public EntityManager getEntityManager() {
        if (emf == null || !emf.isOpen()) {
            emf = Persistence.createEntityManagerFactory("gd-cesPU");
        }
        em = emf.createEntityManager();
        return em;
    }

    public void startTransaction() {
        if (em != null && em.isOpen()) {
            em.getTransaction().begin();
        }
    }

    public void commitTransaction() {
        EntityTransaction transaction = null;
        if (em != null && em.isOpen()) {
            transaction = em.getTransaction();
            if (transaction != null && transaction.isActive()) {
                transaction.commit();
            }
        }
    }

    public void flush() {
        if (em != null && em.isOpen()) {
            em.flush();
        }
    }

    public void clear() {
        if (em != null && em.isOpen()) {
            em.clear();
        }
    }

    public void rollBackTransaction() {
        EntityTransaction transaction = null;
        if (em != null && em.isOpen()) {
            transaction = em.getTransaction();
            if (transaction != null &&
                    transaction.isActive()) {
                transaction.rollback();
            }
        }
    }

    public void closeEntityManager() {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }

}
